<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:text="${config != null ? '编辑配置' : '新增配置'} + ' - 废物回收管理系统'"></title>
    <div th:replace="~{common/common :: header}"></div>
    <link href="https://cdn.jsdelivr.net/npm/jsoneditor@9.10.0/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">
    <script src="https://cdn.jsdelivr.net/npm/jsoneditor@9.10.0/dist/jsoneditor.min.js"></script>
    <style>
        #jsonEditor {
            height: 300px;
        }
        .invalid-feedback {
            display: none;
        }
        .was-validated .form-control:invalid ~ .invalid-feedback {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <!-- 标题栏 -->
        <div class="row mb-3">
            <div class="col">
                <h4 th:text="${config != null ? '编辑配置' : '新增配置'}"></h4>
            </div>
            <div class="col-auto">
                <a href="/config/list" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> 返回列表
                </a>
            </div>
        </div>
        
        <!-- 编辑表单 -->
        <div class="card">
            <div class="card-body">
                <form id="configForm" class="needs-validation" novalidate>
                    <input type="hidden" name="id" th:value="${config?.id}">
                    
                    <div class="row mb-3">
                        <label class="col-sm-2 col-form-label required">配置名称</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="name" 
                                   th:value="${config?.name}" required
                                   pattern="^[\u4e00-\u9fa5a-zA-Z0-9_-]{2,50}$">
                            <div class="invalid-feedback">
                                请输入2-50个字符的配置名称(支持中文、字母、数字、下划线、中划线)
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <label class="col-sm-2 col-form-label required">配置键名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="configKey" 
                                   th:value="${config?.configKey}" required
                                   pattern="^[A-Z][A-Z0-9_]{2,49}$"
                                   th:readonly="${config != null}">
                            <div class="invalid-feedback">
                                请输入3-50个字符的配置键名(必须以大写字母开头,支持大写字母、数字、下划线)
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <label class="col-sm-2 col-form-label required">配置类型</label>
                        <div class="col-sm-10">
                            <select class="form-select" name="type" required
                                    th:readonly="${config != null}">
                                <option value="">请选择配置类型</option>
                                <option value="TEXT" th:selected="${config?.type == 'TEXT'}">文本</option>
                                <option value="NUMBER" th:selected="${config?.type == 'NUMBER'}">数字</option>
                                <option value="BOOLEAN" th:selected="${config?.type == 'BOOLEAN'}">布尔</option>
                                <option value="JSON" th:selected="${config?.type == 'JSON'}">JSON</option>
                            </select>
                            <div class="invalid-feedback">请选择配置类型</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <label class="col-sm-2 col-form-label required">配置键值</label>
                        <div class="col-sm-10">
                            <!-- 文本类型 -->
                            <input type="text" class="form-control config-value" name="configValue" 
                                   data-type="TEXT" style="display: none;"
                                   th:value="${config?.type == 'TEXT' ? config.configValue : ''}"
                                   pattern="^.{1,500}$">
                            
                            <!-- 数字类型 -->
                            <input type="number" class="form-control config-value" name="configValue"
                                   data-type="NUMBER" style="display: none;"
                                   th:value="${config?.type == 'NUMBER' ? config.configValue : ''}"
                                   step="any">
                            
                            <!-- 布尔类型 -->
                            <select class="form-select config-value" name="configValue"
                                    data-type="BOOLEAN" style="display: none;">
                                <option value="true" th:selected="${config?.type == 'BOOLEAN' && config.configValue == 'true'}">是</option>
                                <option value="false" th:selected="${config?.type == 'BOOLEAN' && config.configValue == 'false'}">否</option>
                            </select>
                            
                            <!-- JSON类型 -->
                            <div id="jsonEditor" class="config-value" data-type="JSON" style="display: none;"></div>
                            <input type="hidden" name="configValue" id="jsonValue"
                                   th:value="${config?.type == 'JSON' ? config.configValue : '{}'}">
                            
                            <div class="invalid-feedback">请输入有效的配置键值</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <label class="col-sm-2 col-form-label">备注</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" name="remark" rows="3"
                                      th:text="${config?.remark}"></textarea>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <label class="col-sm-2 col-form-label required">状态</label>
                        <div class="col-sm-10">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="status" 
                                       value="1" required
                                       th:checked="${config == null || config.status == 1}">
                                <label class="form-check-label">启用</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="status" 
                                       value="0" required
                                       th:checked="${config != null && config.status == 0}">
                                <label class="form-check-label">禁用</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-sm-10 offset-sm-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存
                            </button>
                            <a href="/config/list" class="btn btn-secondary">
                                <i class="fas fa-times"></i> 取消
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script th:inline="javascript">
    let jsonEditor = null;
    
    // 初始化JSON编辑器
    function initJsonEditor() {
        const container = document.getElementById('jsonEditor');
        const options = {
            mode: 'tree',
            modes: ['tree', 'code'],
            onChangeText: function(jsonString) {
                document.getElementById('jsonValue').value = jsonString;
            }
        };
        jsonEditor = new JSONEditor(container, options);
        
        // 设置初始值
        const jsonValue = document.getElementById('jsonValue').value;
        try {
            const json = JSON.parse(jsonValue);
            jsonEditor.set(json);
        } catch (e) {
            jsonEditor.set({});
        }
    }
    
    // 根据配置类型显示对应的输入控件
    function showConfigValueInput(type) {
        document.querySelectorAll('.config-value').forEach(el => {
            if (el.dataset.type === type) {
                el.style.display = type === 'JSON' ? 'block' : '';
                el.required = true;
            } else {
                el.style.display = 'none';
                el.required = false;
            }
        });
        
        if (type === 'JSON' && !jsonEditor) {
            initJsonEditor();
        }
    }
    
    // 监听配置类型变化
    document.querySelector('select[name="type"]').addEventListener('change', function(e) {
        showConfigValueInput(e.target.value);
    });
    
    // 检查键名是否存在
    async function checkKeyExists(key, excludeId) {
        const response = await fetch(`/config/check-key?configKey=${key}&excludeId=${excludeId || ''}`);
        return await response.json();
    }
    
    // 表单提交
    document.getElementById('configForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // 表单验证
        if (!this.checkValidity()) {
            this.classList.add('was-validated');
            return;
        }
        
        // 获取表单数据
        const formData = new FormData(this);
        const data = {};
        formData.forEach((value, key) => data[key] = value);
        
        // JSON类型特殊处理
        if (data.type === 'JSON') {
            try {
                JSON.parse(data.configValue);
            } catch (e) {
                showError('请输入有效的JSON格式');
                return;
            }
        }
        
        // 检查键名是否存在
        if (!data.id) {
            const exists = await checkKeyExists(data.configKey);
            if (exists) {
                showError('配置键名已存在');
                return;
            }
        }
        
        // 提交数据
        const url = data.id ? '/config/update' : '/config/create';
        const method = data.id ? 'PUT' : 'POST';
        
        try {
            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
            
            const result = await response.json();
            if (result) {
                showSuccess('保存成功');
                setTimeout(() => location.href = '/config/list', 1000);
            } else {
                showError('保存失败');
            }
        } catch (error) {
            showError('保存失败: ' + error.message);
        }
    });
    
    // 初始化页面
    document.addEventListener('DOMContentLoaded', function() {
        const type = document.querySelector('select[name="type"]').value;
        if (type) {
            showConfigValueInput(type);
        }
    });
    </script>
</body>
</html> 